﻿using ComponentFactory.Krypton.Toolkit;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StableDiffusionTools.Forms
{
    public partial class ConfirmationDialog : KryptonForm
    {
        public bool ResultChecked { get => kryptonCHKConfirmation.Checked; }
        private DialogResult defaultResult;
        public ConfirmationDialog(string text, string caption = "", DialogResult defaultResult = DialogResult.Yes)
        {
            InitializeComponent();

            Size newSize;
            using (var g = this.CreateGraphics())
            {
                newSize = Size.Ceiling(g.MeasureString(text, kryptonLBLInputText.Font, 500));
            }
            
            //Size newSize = TextRenderer.MeasureText(text, lblInputText.Font, new Size(300, 1000), TextFormatFlags.Default | TextFormatFlags.WordBreak);
            ClientSize = new Size(Math.Max(ClientSize.Width, newSize.Width + (ClientSize.Width - kryptonLBLInputText.Width)), newSize.Height + ClientSize.Height);
            kryptonLBLInputText.Text = text;
            this.defaultResult = defaultResult;

            if (!string.IsNullOrEmpty(caption))
                Text = caption;

            KeyDown += (s, e) =>
            {
                if (e.KeyCode == Keys.Escape)
                {
                    DialogResult = DialogResult.Cancel;
                }
            };

            StartPosition = FormStartPosition.CenterParent;
        }

        private void ConfirmationForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(e.CloseReason == CloseReason.UserClosing && kryptonCHKConfirmation.Checked)
            {
                e.Cancel = true;
            }
        }

        public static DialogResult ShowDialogIf(IWin32Window owner, ref bool condition, string text, string caption = "", DialogResult defaultResult = DialogResult.Yes)
        {
            DialogResult result = defaultResult;
            if (condition)
            {
                using (var confirm = new ConfirmationDialog(text, caption, defaultResult))
                {
                    result = confirm.ShowDialog(owner);
                    condition = !confirm.ResultChecked;
                }
            }

            return result;
        }

        private void kryptonCheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (defaultResult == DialogResult.Yes)
            {
                kryptonBTNNo.Enabled = ControlBox = !kryptonCHKConfirmation.Checked;
            }
            else if (defaultResult == DialogResult.No)
            {
                kryptonBTNYes.Enabled = ControlBox = !kryptonCHKConfirmation.Checked;
            }
        }
    }
}
